var copyOrder = {};
var CopyOrder = function () {
    this.map = {};
    this.businessTypesMap = {};
    //初始化
    this.init = function () {
        layui.use(['form'], function () {
            copyOrder.form = layui.form;
        });
        //初始化搜索条件 日期范围组件
        layuiFunciton.layTime({
            elem: '#orderDate'
        });
        var businessTypes = "YWLX_T";
        if ($("#tranType").val() == "1") {//铁路运输
            businessTypes = "YWLX_T";
            //发出站
            copyOrder.initSelect("aStation", "ZD", $("#aStation").val());
            //到站
            copyOrder.initSelect("arriveStation", "ZD", $("#arriveStation").val());
        } else if ($("#tranType").val() == "2") {//水路运输
            businessTypes = "YWLX_S";
            $("#aStationText").text("发出港：");
            $("#arriveStationText").text("到港：");
            //发出港
            copyOrder.initSelect("aStation", "GK", $("#aStation").val());
            //到港
            copyOrder.initSelect("arriveStation", "GK", $("#arriveStation").val());
        } else if ($("#tranType").val() == "3") {//公路运输
            $("#arriveStationText").html("卸货地点：");
            //发出站
            copyOrder.initSelect("aStation", "ZD", $("#aStation").val());
            //卸货地点
            copyOrder.initSelect("arriveStation", "ZHDD", $("#arriveStation").val());
            businessTypes = "YWLX_G";
        }
        //金额验证
        layuiFunciton.moneyValidation("#accountsReceivableAmount");
        //初始化数据字典
        //业务类型
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
            method: 'get',
            maskState: false,
            data: {
                typeCode: businessTypes,
                enabled: 1
            },
            success: function (data) {
                var optionHtml = '<option value="">请选择</option>';
                data.forEach(function (obj, index) {
                    copyOrder.businessTypesMap[obj.valCode] = obj.description;
                    if ($("#businessTypes").val() == obj.valCode) {
                        optionHtml += '<option value="' + obj.valCode + '" selected>' + obj.valName + '</option>';
                    } else {
                        optionHtml += '<option value="' + obj.valCode + '">' + obj.valName + '</option>';
                    }
                });
                $("#businessTypes").html(optionHtml);
            }
        });
        //品名
        copyOrder.initSelect("ofTheGoods", "Of_the_goods");
        //箱型
        copyOrder.initSelect("aBox", "XX");
        //发货单位
        copyOrder.initSelect("deliveryUnit", "FHDW");
        //收货人
        //copyOrder.initSelect("receivingUnit", "SHDW", $("#receivingUnit").val());
        //结算人
        copyOrder.initSelect("settlementPeople", "JSR");
        //司机
        copyOrder.initSelect("driver", "SJ");
        //车牌
        copyOrder.initSelect("licensePlate", "CP");
        //装货地点
        copyOrder.initSelect("standby1", "ZHDD");
        //
        copyOrder.findSelectDict('FYLX');//费用类型
        copyOrder.findSelectDict('SKDW');//收款单位


        copyOrder.findConditions();
        //
        if ($("#whetherSelfTransportValue").val() == 1) {
            $(".driver").show();
            $(".driver").find("input").attr("lay-verify", "required");
            $(".licensePlate").show();
            $(".licensePlate").find("input").attr("lay-verify", "required");
        } else {
            $(".driver").hide();
            $(".driver").find("input").removeAttr("lay-verify");
            $(".licensePlate").hide();
            $(".licensePlate").find("input").removeAttr("lay-verify");
        }
    };
    /**
     *
     * @param costType  费用类型
     * @param receivingUnit  收款单位
     * @param amountPayable  应付金额
     * @param realPayTotalAmount  实付金额
     * @param note   备注
     */
    this.addRow = function (costType, receivingUnit, amountPayable, realPayTotalAmount, note) {
        var rowHtml = `<tr>
                        <td>
                            <select name="" class="">
                            ` + copyOrder.joinSelect('FYLX', costType) + `
                           </select>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money" value="` + (amountPayable ? amountPayable : '') + `" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money"  value="` + (realPayTotalAmount ? realPayTotalAmount : '') + `" type="text"/>
                        </td>
                        <td>
                         <select name="" class=""  lay-search="">
                            ` + copyOrder.joinSelect('SKDW', receivingUnit) + `
                           </select>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit" value="` + (note ? note : '') + `" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"><a href="javascript:void(0)"
                                                             style="color:#009feb;padding-left: 8px;"
                                                             onclick="copyOrder.delRow(this)">删除</a></div>
                        </td>
                    </tr>`;
        $("#row").append(rowHtml);
        copyOrder.form.render("select");
        layuiFunciton.moneyValidation(".money");
    };
    //删除一行
    this.delRow = function (obj) {
        $(obj).parents("tr").remove();
    };
    //拼接Select
    this.joinSelect = function (code, defaultCode) {
        var optionHtml = '<option value="">请选择</option>';
        if(copyOrder.map[code])
        copyOrder.map[code].forEach(function (obj, index) {
            if (obj.valCode == defaultCode) {
                optionHtml += '<option value="' + obj.valCode + '" selected>' + obj.valName + '</option>';
            } else {
                optionHtml += '<option value="' + obj.valCode + '">' + obj.valName + '</option>';
            }
        });
        return optionHtml;
    };
    //查询
    this.findSelectDict = function (code) {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
            method: 'get',
            maskState: false,
            data: {
                typeCode: code,
                enabled: 1
            },
            success: function (data) {
                copyOrder.map[code] = data;
            }
        });
    };
    //事件绑定
    this.event = function () {
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'checkbox',   //
            filterName: 'whetherSelfTransport',
            returnData: function (obj) {
                if (obj.elem.checked) {
                    //司机
                    copyOrder.initSelect("driver", "SJ");
                    //车牌
                    copyOrder.initSelect("licensePlate", "CP");
                    $(".driver").show();
                    $(".driver").find("input").attr("lay-verify", "required");
                    $(".licensePlate").show();
                    $(".licensePlate").find("input").attr("lay-verify", "required");
                } else {
                    $(".driver").hide();
                    $(".driver").find("input").removeAttr("lay-verify");
                    $(".licensePlate").hide();
                    $(".licensePlate").find("input").removeAttr("lay-verify");
                }
            }
        });
        //监听选择业务类型
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'select',   //
            filterName: 'businessTypes',
            returnData: function (obj) {
                $("#row").html("");
                if (obj.value) {
                    var description = copyOrder.businessTypesMap[obj.value];
                    if (description) {
                        layuiFunciton.ajaxRequest({
                            url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
                            method: 'get',
                            maskState: false,
                            data: {
                                typeCode: 'FYLX',  //费用类型
                                enabled: 1,
                                strs: description
                            },
                            success: function (data) {
                                data.forEach(function (obj, index) {
                                    copyOrder.addRow(obj.valCode, obj.description);
                                });
                            }
                        });
                    }
                }
            }
        });
        //保存
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'submit',   //
            filterName: 'copyOrder',
            returnData: function (obj) {
                $("#states").val(-1);
                copyOrder.submitData(obj);
            }
        });
        //审核
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'submit',   //
            filterName: 'audit',
            returnData: function (obj) {
                $("#states").val(0);
                copyOrder.submitData(obj);
            }
        });
    };
    this.audit = function () {
        $(".required").attr("lay-verify", "required");
    };
    this.copyOrder = function () {
        $(".required").removeAttr("lay-verify");
    };
    //提交数据
    this.submitData = function (obj) {
        var formJSON = {};
        var list = $("#copyFormOrder").serializeArray();
        for (var i = 0; i < list.length; i++) {
            formJSON[list[i].name] = list[i].value;
        }
        //获取费用类型
        var trs = $("#row").find("tr");
        var costTypeObj = {}, returnCostName, index = -1, tf = false;
        var copeWithTotalAmount = 0.00;//应付总金额
        var realPayTotalAmount = 0.00;//实付总金额
        var batchNumber = new Date().getTime();//批次号
        for (var k = 0; k < trs.length; k++) {
            var tds = trs.eq(k).find("td");
            //费用类型 字典值
            var costType = tds.eq(0).find("select").val();
            formJSON['wbScheduleTypesList[' + k + '].costType'] = costType;
            var costName = tds.eq(0).find("select").find("option:selected").text();
            //应付金额
            var amountPayable = tds.eq(1).find("input").val();
            formJSON['wbScheduleTypesList[' + k + '].amountPayable'] = amountPayable;
            copeWithTotalAmount = (Number(copeWithTotalAmount) + Number(amountPayable ? amountPayable : 0.00)).toFixed(2);
            //实付金额
            var amountRealPay = tds.eq(2).find("input").val();
            formJSON['wbScheduleTypesList[' + k + '].amountRealPay'] = amountRealPay;
            realPayTotalAmount = (Number(realPayTotalAmount) + Number(amountRealPay ? amountRealPay : 0.00)).toFixed(2);
            //收款单位 字典值
            var receivingUnit = tds.eq(3).find("select").val();
            formJSON['wbScheduleTypesList[' + k + '].receivingUnit'] = receivingUnit;
            //备注
            var note = tds.eq(4).find("input").val();
            formJSON['wbScheduleTypesList[' + k + '].note'] = note;

            //验证
            if (costTypeObj[costType]) {
                if (costTypeObj[costType] == receivingUnit) {
                    index = k;
                    returnCostName = costName;
                }
            } else {
                if (costType) {
                    costTypeObj[costType] = receivingUnit;
                } else {
                    tf = true;
                }
            }
            //
            formJSON['wbScheduleTypesList[' + k + '].states'] = 0;
            formJSON['wbScheduleTypesList[' + k + '].batchNumber'] = batchNumber;
            formJSON['wbScheduleTypesList[' + k + '].creationTime'] = copyOrder.dateFtt('yyyy-MM-dd hh:mm:ss', new Date());
        }
        //费用总额
        formJSON.totalCosts = copeWithTotalAmount;
        if ($("#states").val() == 0) {
            if (trs.length == 0) {
                layuiFunciton.warn('费用明细不能为空！');
                return;
            }
            if (tf) {
                layuiFunciton.warn('费用类型不能为空！');
                return;
            }
            if (index > -1) {
                layuiFunciton.warn('费用类型“' + returnCostName + '”重复！');
                return;
            }
        }
        //请求后台
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/shipping/order/insert',
            method: 'post',
            data: formJSON,
            success: function (data) {
                if (data > 0) {
                    layuiFunciton.success("添加成功！", function () {
                        layuiFunciton.closeOpen();
                    })
                } else {
                    layuiFunciton.warn('操作失败！');
                }
            }, error: function () {
                layuiFunciton.closeOpen();
            }
        });
    };
    //时间格式化
    this.dateFtt = function (fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,     //月份
            "d+": date.getDate(),     //日
            "h+": date.getHours(),     //小时
            "m+": date.getMinutes(),     //分
            "s+": date.getSeconds(),     //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()    //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    //查询费用明细
    this.findConditions = function () {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/schedule/types/wbScheduleTypes',
            method: 'get',
            maskState: false,
            data: {
                orderCode: $("#orderCode").val(),
                states: 0
            },
            success: function (data) {
                data.forEach(function (obj, index) {
                    copyOrder.addRow(obj.costType, obj.receivingUnit, obj.amountPayable, obj.amountRealPay, obj.note);
                });
            }
        });
    };
    //初始化input 搜索
    this.initSelect = function (item,typeCode) {
        $("#"+item).attr("readonly","");
        //引入自定义插件
        layui.config({
            base: '/public/plugin/tableSelect/' //设置自定义插件路径:根据实际路径进行设置
        }).use(['tableSelect'], function() {
            var tableSelect = layui.tableSelect;
            tableSelect.render({
                elem: '#'+item,	//定义输入框input对象
                checkedKey: 'valCode', //表格的唯一建值，非常重要，影响到选中状态 必填
                searchKey: 'valName',	//搜索输入框的name值 默认keyword
                searchPlaceholder: '关键词搜索',	//搜索输入框的提示文字 默认关键词搜索
                table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                    url:layuiFunciton.URL + '/sys/dictVal/getByTypeCode?typeCode='+typeCode,
                    page:false,
                    cols: [[
                        {field: 'valName', title: '请选择（双击）',align: "center"}
                    ]]
                },
                done: function (elem, data) {
                    $('#'+item).val(data.data[0].valName);
                    $('#'+item).siblings("input[type='hidden']").val(data.data[0].valCode);
                }
            });
            var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
            if($('#'+item).val()){
                $("#" + item).after('<input type="hidden" name="'+item+'" value="'+$('#'+item).val()+'" >');
                $('#'+item).val(dictMap[$('#'+item).val()]);
            }else{
                $("#" + item).after('<input type="hidden" name="'+item+'" value="" >');
            }
        });
    }
};
function pageReady() {
    copyOrder = new CopyOrder();
    copyOrder.init();
    copyOrder.event();
}